/**
 * 
 */
package com.jeecms.wicool.weixin;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeecms.wicool.util.HttpKit;

/**
 * @author spring
 * 
 */
public class WeiXinUtil {
	private static final String CREATE_GROUP = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token=";
	
	private static final String UPDATE_GROUP = "https://api.weixin.qq.com/cgi-bin/groups/update?access_token=";
	
	private static final String UPDATE_USER_GROUP = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=";
	
	private static final String BATCH_UPDATE_USER_GROUP = "https://api.weixin.qq.com/cgi-bin/groups/members/batchupdate?access_token=";

	private static final String DELETE_GROUP = "https://api.weixin.qq.com/cgi-bin/groups/delete?access_token=";
	
	private static final String REFRESH_TOKEN = "http://www.gsskx.com/skx/refreshToken.action?appId=weixinskx!@123";

	/**
	 * 获取微信的TOKEN
	 * @return
	 */
	public static String getAccessToken(){
	    WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
		DataSource ds = (DataSource)  wac.getBean("dataSource");
		QueryRunner runner = new QueryRunner(ds);
		try {
			WeiXinAccessToken token = getWeiXinAccessToken(runner);
			if(System.currentTimeMillis() > token.getExpireTime().longValue()){
				String returnMsg = HttpKit.get(REFRESH_TOKEN);
				if("success".equals(returnMsg)){
					 token = getWeiXinAccessToken(runner);
				}
			}
			return token.getAccessToken();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private static WeiXinAccessToken getWeiXinAccessToken(QueryRunner runner) throws SQLException{
		return runner.query("select * from access_token", new ResultSetHandler<WeiXinAccessToken>() {

			@Override
			public WeiXinAccessToken handle(ResultSet arg0) throws SQLException {
				WeiXinAccessToken obj = new WeiXinAccessToken();
				if(arg0.next()){
					obj.setAccessToken(arg0.getString("access_token"));
					obj.setExpireTime(arg0.getLong("expire_time"));
					obj.setId(arg0.getInt("id"));
				}
				return obj;
			}
			
		});
	}
	
	/**
	 * 创建用户组
	 * @param accessToken
	 * @param name
	 * @return
	 */
	public static WeiXinUserGroupBean createGroup(String name){
		String accessToken = getAccessToken();
		if(StringUtils.isBlank(accessToken)){
			System.out.println("----------------------------->没有获取到有效的accessToken");
			return null;
		}
		String request = "{\"group\":{\"name\":\""+name+"\"}}";
		try {
			System.out.println("----------------------------->请求数据："+request);
			String jsonResult = HttpKit.post(CREATE_GROUP+accessToken, request);
			System.out.println("----------------------------->响应数据："+jsonResult);
			if(jsonResult.startsWith("{") && jsonResult.endsWith("}")){
				JSONObject json = JSONObject.parseObject(jsonResult);
				if("40001".equals(json.getString("errcode")) || "42001".equals(json.getString("errcode"))){
					String returnMsg = HttpKit.get(REFRESH_TOKEN);
					if("success".equals(returnMsg)){
						accessToken = getAccessToken();
						if(StringUtils.isBlank(accessToken)){
							System.out.println("----------------------------->没有获取到有效的accessToken");
							return null;
						}
						System.out.println("----------------------------->再次请求数据："+request);
						jsonResult = HttpKit.post(CREATE_GROUP+accessToken, request);
						System.out.println("----------------------------->再次响应数据："+jsonResult);
					}
				}
			}
			JSONObject json = JSONObject.parseObject(jsonResult);
			if(StringUtils.isBlank(json.getString("errcode"))){
				WeiXinUserGroupBean bean = new WeiXinUserGroupBean();
				bean.setId(json.getJSONObject("group").getInteger("id"));
				bean.setName(json.getJSONObject("group").getString("name"));
				return bean;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 更新用户组
	 * @param accessToken
	 * @param bean
	 * @return
	 */
	public static Boolean updateGroup(WeiXinUserGroupBean bean){
		String accessToken = getAccessToken();
		if(StringUtils.isBlank(accessToken)){
			System.out.println("----------------------------->没有获取到有效的accessToken");
			return false;
		}
		String request = "{\"group\":"+JSONObject.toJSONString(bean)+"}";
		try {
			System.out.println("----------------------------->请求数据："+request);
			String jsonResult = HttpKit.post(UPDATE_GROUP+accessToken, request);
			System.out.println("----------------------------->响应数据："+jsonResult);
			if(jsonResult.startsWith("{") && jsonResult.endsWith("}")){
				JSONObject json = JSONObject.parseObject(jsonResult);
				if("40001".equals(json.getString("errcode")) || "42001".equals(json.getString("errcode"))){
					String returnMsg = HttpKit.get(REFRESH_TOKEN);
					if("success".equals(returnMsg)){
						accessToken = getAccessToken();
						if(StringUtils.isBlank(accessToken)){
							System.out.println("----------------------------->没有获取到有效的accessToken");
							return null;
						}
						System.out.println("----------------------------->再次请求数据："+request);
						jsonResult = HttpKit.post(UPDATE_GROUP+accessToken, request);
						System.out.println("----------------------------->再次响应数据："+jsonResult);
					}
				}
			}
			JSONObject json = JSONObject.parseObject(jsonResult);
			if(!StringUtils.isBlank(json.getString("errcode")) && json.getString("errcode").equals("0")){
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 更新用户的分组信息
	 * @param accessToken
	 * @param bean
	 * @return
	 */
	public static Boolean updateUserGroup(WeiXinUserBean bean){
		String accessToken = getAccessToken();
		if(StringUtils.isBlank(accessToken)){
			System.out.println("----------------------------->没有获取到有效的accessToken");
			return false;
		}
		String request = JSONObject.toJSONString(bean);
		try {
			System.out.println("----------------------------->请求数据："+request);
			String jsonResult = HttpKit.post(UPDATE_USER_GROUP+accessToken, request);
			System.out.println("----------------------------->响应数据："+jsonResult);
			if(jsonResult.startsWith("{") && jsonResult.endsWith("}")){
				JSONObject json = JSONObject.parseObject(jsonResult);
				if("40001".equals(json.getString("errcode")) || "42001".equals(json.getString("errcode"))){
					String returnMsg = HttpKit.get(REFRESH_TOKEN);
					if("success".equals(returnMsg)){
						accessToken = getAccessToken();
						if(StringUtils.isBlank(accessToken)){
							System.out.println("----------------------------->没有获取到有效的accessToken");
							return null;
						}
						System.out.println("----------------------------->再次请求数据："+request);
						jsonResult = HttpKit.post(UPDATE_USER_GROUP+accessToken, request);
						System.out.println("----------------------------->再次响应数据："+jsonResult);
					}
				}
			}
			JSONObject json = JSONObject.parseObject(jsonResult);
			if(!StringUtils.isBlank(json.getString("errcode")) && json.getString("errcode").equals("0")){
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 批量更新用户的分组信息
	 * @param accessToken
	 * @param openIds
	 * @param groupId
	 * @return
	 */
	public static Boolean batchUpdateUserGroup(List<String> openIds,String groupId){
		String accessToken = getAccessToken();
		if(StringUtils.isBlank(accessToken)){
			System.out.println("----------------------------->没有获取到有效的accessToken");
			return false;
		}
		String request = "{\"openid_list\":"+JSONArray.toJSONString(openIds)+",\"to_groupid\":"+groupId+"}";
		try {
			System.out.println("----------------------------->请求数据："+request);
			String jsonResult = HttpKit.post(BATCH_UPDATE_USER_GROUP+accessToken, request);
			System.out.println("----------------------------->响应数据："+jsonResult);
			if(jsonResult.startsWith("{") && jsonResult.endsWith("}")){
				JSONObject json = JSONObject.parseObject(jsonResult);
				if("40001".equals(json.getString("errcode")) || "42001".equals(json.getString("errcode"))){
					String returnMsg = HttpKit.get(REFRESH_TOKEN);
					if("success".equals(returnMsg)){
						accessToken = getAccessToken();
						if(StringUtils.isBlank(accessToken)){
							System.out.println("----------------------------->没有获取到有效的accessToken");
							return null;
						}
						System.out.println("----------------------------->再次请求数据："+request);
						jsonResult = HttpKit.post(BATCH_UPDATE_USER_GROUP+accessToken, request);
						System.out.println("----------------------------->再次响应数据："+jsonResult);
					}
				}
			}
			JSONObject json = JSONObject.parseObject(jsonResult);
			if(!StringUtils.isBlank(json.getString("errcode")) && json.getString("errcode").equals("0")){
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 删除用户组
	 * @param accessToken
	 * @param id
	 * @return
	 */
	public static Boolean deleteGroup(String id){
		String accessToken = getAccessToken();
		if(StringUtils.isBlank(accessToken)){
			System.out.println("----------------------------->没有获取到有效的accessToken");
			return false;
		}
		String request = "{\"group\":{\"id\":"+id+"}}";
		try {
			System.out.println("----------------------------->请求数据："+request);
			String jsonResult = HttpKit.post(DELETE_GROUP+accessToken, request);
			System.out.println("----------------------------->响应数据："+jsonResult);
			if(jsonResult.startsWith("{") && jsonResult.endsWith("}")){
				JSONObject json = JSONObject.parseObject(jsonResult);
				if("40001".equals(json.getString("errcode")) || "42001".equals(json.getString("errcode"))){
					String returnMsg = HttpKit.get(REFRESH_TOKEN);
					if("success".equals(returnMsg)){
						accessToken = getAccessToken();
						if(StringUtils.isBlank(accessToken)){
							System.out.println("----------------------------->没有获取到有效的accessToken");
							return null;
						}
						System.out.println("----------------------------->再次请求数据："+request);
						jsonResult = HttpKit.post(DELETE_GROUP+accessToken, request);
						System.out.println("----------------------------->再次响应数据："+jsonResult);
					}
				}
			}
			JSONObject json = JSONObject.parseObject(jsonResult);
			if(!StringUtils.isBlank(json.getString("errcode")) && json.getString("errcode").equals("0")){
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public static void main(String[] args) {
		String url = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token="+getAccessToken();
		System.out.println(url);
		String jsonResult = HttpKit.post(url, null);
		System.out.println(jsonResult);
	}
}
